package com.nurt.controller.order;

import com.alibaba.fastjson2.JSONObject;
import com.nurt.dto.ResultDto;
import com.nurt.entity.OrderDishEntity;
import com.nurt.service.OrderService;
import com.nurt.service.impl.OrderServiceImpl;
import com.nurt.utils.ServletHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

/**
 * 处理与订单菜品相关请求的控制器。
 * {@code @WebServlet} 注解指定了该 servlet 的 URL 模式。
 */
@WebServlet(urlPatterns = {"/orderDishes/*"})
public class OrderDishController extends HttpServlet {
    /**
     * 订单服务接口的实现类实例，用于处理订单相关的业务逻辑。
     */
    private OrderService orderService;

    /**
     * 初始化控制器，实例化订单服务。
     */
    public void init() {
        orderService = new OrderServiceImpl();
    }

    /**
     * 处理 GET 请求，根据路径信息获取指定订单的菜品列表。
     * @param request HTTP 请求对象
     * @param response HTTP 响应对象
     * @throws ServletException Servlet 相关的异常
     * @throws IOException 输入输出异常
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        String[] pathParts = pathInfo.split("/");
        int orderId = Integer.parseInt(pathParts[1]);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            List<OrderDishEntity> orderDishes = orderService.getCartContents(orderId);
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(ResultDto.success(orderDishes));
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write((String) ResultDto.error("Internal Server Error"));
        }
    }

    /**
     * 处理 POST 请求，将菜品添加到指定订单的购物车。
     * @param request HTTP 请求对象，包含订单和菜品信息
     * @param response HTTP 响应对象
     * @throws ServletException Servlet 相关的异常
     * @throws IOException 输入输出异常
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JSONObject jsonObject = ServletHelper.getRequestBodyAsJson(request);
        int orderId = jsonObject.getIntValue("orderId");
        int dishId = jsonObject.getIntValue("dishId");

        int orderDishId = orderService.addToCart(orderId, dishId);
        response.setStatus(HttpServletResponse.SC_CREATED);
        response.getWriter().write(ResultDto.success(orderDishId));
    }

    /**
     * 处理 PUT 请求，更新指定订单中菜品的数量。
     * @param request HTTP 请求对象，包含订单、菜品和数量信息
     * @param response HTTP 响应对象
     * @throws ServletException Servlet 相关的异常
     * @throws IOException 输入输出异常
     */
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JSONObject jsonObject = ServletHelper.getRequestBodyAsJson(request);
        int orderId = jsonObject.getIntValue("orderId");
        int dishId = jsonObject.getIntValue("dishId");
        int quantity = jsonObject.getIntValue("quantity");

        OrderDishEntity orderDish = new OrderDishEntity();
        orderDish.setOrderId(orderId);
        orderDish.setDishId(dishId);
        orderDish.setQuantity(quantity);

        orderService.updateOrderDish(orderDish);
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(ResultDto.success("Order dish updated successfully"));
    }

    /**
     * 处理 DELETE 请求，从指定订单的购物车中移除菜品。
     * @param request HTTP 请求对象，包含订单和菜品信息
     * @param response HTTP 响应对象
     * @throws ServletException Servlet 相关的异常
     * @throws IOException 输入输出异常
     */
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        String[] pathParts = pathInfo.split("/");
        int orderId = Integer.parseInt(pathParts[1]);
        int dishId = Integer.parseInt(pathParts[3]);

        orderService.removeFromCart(orderId, dishId);
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
